package com.lynn.cons.common;

import ohos.app.Context;
import ohos.data.DatabaseHelper;
import ohos.data.orm.OrmContext;
import ohos.data.orm.OrmDatabase;
import ohos.data.orm.OrmObject;
import ohos.data.orm.OrmPredicates;

import java.util.List;
import java.util.function.Consumer;

public class OrmHelper {
    private static DatabaseHelper HELPER;
    private static Class CLASS;

    /**
     * 上下文注册 应用启动就注册
     *
     * @param context ohos.app.Context
     */
    public static <DataBase extends OrmDatabase> void Register(Context context, Class<DataBase> zClass) {
        if (HELPER == null) {
            HELPER = new DatabaseHelper(context);
        }
        CLASS = zClass;
    }

    private static class SingletonClassInstance {
        private static final OrmHelper instance = new OrmHelper();
    }

    private OrmHelper() {
    }

    public static final OrmHelper getInstance() {
        return SingletonClassInstance.instance;
    }

    private OrmContext getContext() {
        String name = CLASS.getSimpleName();
        return HELPER.getOrmContext(name, name + ".db", CLASS);
    }

    public <T extends OrmObject> boolean insert(T object) {
        OrmContext ormContext = getContext();
        boolean flag = ormContext.insert(object);
        ormContext.flush();
        ormContext.close();
        return flag;
    }
    public <T extends OrmObject> boolean update(T object) {
        OrmContext ormContext = getContext();
        boolean flag = ormContext.update(object);
        ormContext.flush();
        ormContext.close();
        return flag;
    }
    public <T extends OrmObject> boolean detete(T object) {
        OrmContext ormContext = getContext();
        boolean flag = ormContext.delete(object);
        ormContext.flush();
        ormContext.close();
        return flag;
    }
    /**
     * 查询数据
     *
     * @param func
     * @param zClass
     * @param <T>
     * @return
     */
    public <T extends OrmObject> List<T> query(Consumer<OrmPredicates> func, Class<T> zClass) {
        OrmContext ormContext = getContext();
        OrmPredicates predicates = ormContext.where(zClass);
        func.accept(predicates);
        List<T> list = ormContext.query(predicates);
        ormContext.flush();
        ormContext.close();
        return list;
    }
}
